document.addEventListener('DOMContentLoaded', function() {
    // 获取URL中的令牌
    const urlParams = new URLSearchParams(window.location.search);
    const token = urlParams.get('token');
    const resetTokenInput = document.getElementById('reset-token');
    const resetForm = document.getElementById('reset-password-form');
    const successMessage = document.getElementById('success-message');
    const errorMessage = document.getElementById('error-message');
    
    // 存储令牌
    resetTokenInput.value = token;
    
    // 验证令牌有效性
    let isValidToken = false;
    let userEmail = '';
    
    if (token) {
        try {
            // 解码令牌（实际应用中应使用更安全的验证方式）
            const decodedToken = atob(token);
            const [email, timestamp] = decodedToken.split('-');
            const tokenAge = (new Date().getTime() - timestamp) / (1000 * 60 * 60); // 小时
            
            // 检查令牌是否在24小时有效期内
            if (tokenAge < 24) {
                isValidToken = true;
                userEmail = email;
            }
        } catch (e) {
            console.error('令牌验证失败', e);
        }
    }
    
    // 显示相应的消息
    if (!isValidToken) {
        resetForm.classList.add('hidden');
        errorMessage.classList.remove('hidden');
    }
    
    // 密码显示/隐藏切换
    document.querySelectorAll('.toggle-password').forEach(button => {
        button.addEventListener('click', function() {
            const targetId = this.getAttribute('data-target');
            const passwordInput = document.getElementById(targetId);
            const icon = this.querySelector('i');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            } else {
                passwordInput.type = 'password';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            }
        });
    });
    
    // 表单提交处理
    resetForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const newPassword = document.getElementById('new-password').value;
        const confirmPassword = document.getElementById('confirm-password').value;
        const newPasswordError = document.getElementById('new-password-error');
        const confirmPasswordError = document.getElementById('confirm-password-error');
        let isValid = true;
        
        // 清除错误信息
        newPasswordError.textContent = '';
        confirmPasswordError.textContent = '';
        
        // 验证新密码
        if (newPassword.length < 8) {
            newPasswordError.textContent = '密码长度至少8位';
            isValid = false;
        } else if (!/\d/.test(newPassword) || !/[a-zA-Z]/.test(newPassword)) {
            newPasswordError.textContent = '密码必须包含字母和数字';
            isValid = false;
        }
        
        // 验证确认密码
        if (newPassword !== confirmPassword) {
            confirmPasswordError.textContent = '两次输入的密码不一致';
            isValid = false;
        }
        
        if (!isValid) return;
        
        // 更新用户密码
        let users = JSON.parse(localStorage.getItem('registeredUsers')) || [];
        const userIndex = users.findIndex(user => user.email === userEmail);
        
        if (userIndex !== -1) {
            users[userIndex].password = newPassword;
            localStorage.setItem('registeredUsers', JSON.stringify(users));
            
            // 显示成功消息并隐藏表单
            resetForm.classList.add('hidden');
            successMessage.classList.remove('hidden');
            
            // 3秒后跳转到登录页
            setTimeout(() => {
                window.location.href = 'index.html';
            }, 3000);
        } else {
            errorMessage.textContent = '未找到该用户';
            errorMessage.classList.remove('hidden');
        }
    });
});
